//////////////////////////////////////////////////////////////////////////////////
//	Copyright 2011 by Yosef Grabivker, ryuho@homenetworksoft.com
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//////////////////////////////////////////////////////////////////////////////////

//	App
#include <wx/wx.h>
#include <wx/cmdline.h>
#include <wx/snglinst.h>
#include "rcmdapp.h"
#include "mainwnd.h"
#include "rtsocket.h"


#define APP_PORT wxT("43765")
#define APP_ID wxT("E32F8C4E-2C8E-407f-916F-35E1D1E0B3C6")

static const wxCmdLineEntryDesc cmdLineDesc[] =
{
	{ wxCMD_LINE_SWITCH, NULL, SWITCH_SHOW_MINIMIZED, "start minimized", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
	{ wxCMD_LINE_SWITCH, NULL, SWITCH_DISABLE_SINGLE, "disable instance check", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
	{ wxCMD_LINE_NONE }
};


CRCMDApp::CRCMDApp():m_pInstanceChecker(NULL)
{
}

CRCMDApp::~CRCMDApp()
{
}

int  CRCMDApp::OnExit()
{
	if ( m_pInstanceChecker )
	{
		delete m_pInstanceChecker;
		m_pInstanceChecker = NULL;
	}

	return 0;
}

bool CRCMDApp::OnInit()
{
	bool bRes(false);

	try
	{
		const wxString strAppIdName = wxString::Format(APP_ID);
		m_pInstanceChecker = new wxSingleInstanceChecker(strAppIdName);

		if (!m_pInstanceChecker)
		{
			wxLogError(_("Low memory, aborting."));
			return false;
		}

		wxCmdLineParser parser(wxApp::argc, wxApp::argv);
		parser.SetDesc(cmdLineDesc);
		parser.SetSwitchChars( wxT("-"));
		parser.Parse();

		if ( !parser.Found(SWITCH_DISABLE_SINGLE) )
		{
			if ( m_pInstanceChecker->IsAnotherRunning() )
			{
				//wxLogError(_("Another program instance is already running, aborting."));

				wxString hostName;
				hostName = wxGetHostName();

				wxDDEClient client;
				client.MakeConnection(hostName, APP_PORT, APP_ID);

				delete m_pInstanceChecker;
				return false;
			}
		}

		CRTSocket::Initialize();
		
		InitLang();

		wxString strAppName;

		strAppName = _("Router Commander");

		m_pWnd = new CMainWnd(m_config,  strAppName, wxPoint(0,0),
				#ifdef LINUX
				wxSize(980,680)
				#else
				wxSize(840,760)
				#endif
		);
		
		if ( m_pWnd )
		{
			SetTopWindow(m_pWnd);
			m_pWnd->StartUp();
		
			if ( parser.Found(SWITCH_SHOW_MINIMIZED) )
			{
				m_pWnd->Show(false);
			}
			else
			{
				m_pWnd->Show();
			}

			Create (APP_PORT);
		
			bRes = true;
		}
	}
	catch(...)
	{
		
	}
	
	return bRes;
}

void CRCMDApp::InitLang()
{
	try
	{
		m_locale.Init( m_config.GetLangId() );
		
	}catch(...) {}
	
	#ifdef LINUX
	wxLocale::AddCatalogLookupPathPrefix(wxT("/usr/share/docs/routercommander/i18n"));
	#else
	wxLocale::AddCatalogLookupPathPrefix(wxT("i18n"));
	#endif
	m_locale.AddCatalog(wxT("routercmd"));
	 
#ifdef LINUX
    {
        wxLogNull noLog;
        m_locale.AddCatalog(_T("fileutils"));
    }
#endif
}

void CRCMDApp::Restart()
{
	wxString strMe = wxApp::argv[0];
	strMe+=wxT(" --d");
	wxExecute(strMe);
}

wxString CRCMDApp::GetInstallDir()
{
	wxString strMe = wxApp::argv[0];

	int nPos;

	#ifdef WIN32
	nPos = strMe.find_last_of(wxT('\\'));
	#else
	nPos = strMe.find_last_of(wxT('/'));
	#endif

	if ( wxNOT_FOUND!=nPos )
	{
		strMe.erase(nPos+1);
	}

	return strMe;
}

wxString CRCMDApp::GetImageDir()
{
	wxString strCur = GetInstallDir();
	strCur+=wxT("images");

	#ifdef WIN32
	strCur+=wxT('\\');
	#else
	strCur=wxT("/usr/share/docs/routercommander/images/");
	#endif

	return strCur;
}

wxString CRCMDApp::GetMAPDir()
{
	wxString strCur = GetInstallDir();
	strCur+=wxT("ip2country");

#ifdef WIN32
	strCur+=wxT('\\');
#else
	strCur=wxT("/usr/share/docs/routercommander/ip2country/");
#endif

	return strCur;
}

void CRCMDApp::RunHelp(const wxString& strTopic)
{
	wxString strURL=wxT("http://routercommander.com/help");
	strURL+=strTopic;
	wxLaunchDefaultBrowser(strURL);
}

wxConnectionBase *  CRCMDApp::OnAcceptConnection (const wxString &topic)
{
	if ( topic==APP_ID )
	{
		if (m_pWnd)
		{
			m_pWnd->Show();
			m_pWnd->Restore();
			m_pWnd->Raise();

			return new wxDDEConnection();
		}
	}

	return NULL;
}